from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Article
from .serializers import ArticleSerializer
from rest_framework.permissions import IsAuthenticated


# Create your views here.

class ArticleAPIView(APIView):
    def get(self, request):
        articles = Article.objects.all()  # 拿到的是QuerySet对象，需要序列化转成json
        serializer = ArticleSerializer(articles, many=True)  # 序列化 many=True表示有多个对象
        return Response({"code": 200, "data": serializer.data})


class SearchAPIView(APIView):
    def post(self, request):
        articles = Article.objects.filter(question__icontains=request.data.get('question'))
        serializer = ArticleSerializer(articles, many=True)
        return Response({"code": 200, "data": serializer.data})


class PublishAPIView(APIView):
    permission_classes = [IsAuthenticated]  # 权限认证 IsAuthenticated必须登录用户才能访问,token认证
    # 在请求时，在token前添加字符串Bearer和空格“bearer <token>”，如：Authorization: Bearer <token>

    def post(self, request):
        serializer = ArticleSerializer(data=request.data)  # 创建序列化器对象，传入请求数据
        if serializer.is_valid():
            serializer.save()
            return Response({'code': 200, 'message': '发布成功'})
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
